#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
from __future__ import absolute_import

__author__ = 'hkh'
__version__ = 1.0
__date__ = '22/01/2019'

import re
import os
root_dir = os.path.abspath(os.path.dirname(__file__))


def updateBinding():
    pattern_1 = 'CALLBACK_FUNC_TYPE = None'
    repl_1 = \
"""
CALLBACK_FUNC_TYPE = None
def loadLibMVSDK():
    import os
    is_x86 = (platform.architecture()[0] == '32bit')
    root_dir = os.path.abspath(os.path.dirname(__file__))
    lib_name = ''
    if is_x86:
        lib_name = 'x86/libMVSDK.so'
    else:
        lib_name = 'x64/libMVSDK.so'
    lib_path = os.path.join(root_dir, '../lib/' , lib_name)
    _sdk = cdll.LoadLibrary(os.path.abspath(lib_path))
    return _sdk


def loadWinMVSDK():
    import os
    is_x86 = (platform.architecture()[0] == '32bit')
    root_dir = os.path.abspath(os.path.dirname(__file__))
    lib_name = ''
    if is_x86:
        lib_name = 'win_x86/MVCAMSDK.dll'
    else:
        lib_name = 'win_x64/MVCAMSDK_X64.dll'
    lib_path = os.path.join(root_dir, '../lib/', lib_name)
    _sdk = windll.LoadLibrary(os.path.abspath(lib_path))
    return _sdk
"""

    pattern_2 = '_sdk = cdll.LoadLibrary\("libMVSDK.so"\)'
    repl_2 = "_sdk = loadLibMVSDK()"

    pattern_3 = 'super\(CameraException, self\).__init__\(\)'
    repl_3 = 'super(CameraException, self).__init__(error_code)'

    pattern_4 = '_sdk = windll.MVCAMSDK if is_x86 else windll.MVCAMSDK_X64'
    repl_4 = '_sdk = loadWinMVSDK()'

    read_path = os.path.join(root_dir, 'mvsdk.py')
    write_path = os.path.join(root_dir, 'mvsdk_modify.py')

    with open(read_path) as f:
        data = f.readlines()
        for i in range(len(data)):
            modify_str = re.sub(pattern_1, repl_1, data[i])
            modify_str = re.sub(pattern_2, repl_2, modify_str)
            modify_str = re.sub(pattern_3, repl_3, modify_str)
            modify_str = re.sub(pattern_4, repl_4, modify_str)
            if modify_str != data[i]:
                # print(modify_str)
                data[i] = modify_str

    with open(write_path, 'w') as f:
        f.writelines(data)

if __name__ == '__main__':
    updateBinding()